#coding: utf-8

import MySQLdb
import config

def get_connection():
    conn = MySQLdb.connect(host = config.MYSQL_HOST,
                        port = config.MYSQL_PORT,
                        user = config.MYSQL_USER,
                        passwd = config.MYSQL_PASSWORD,
                        db = config.CNBOOKS_DB)
    return conn

class MySQLUtil(object):
    def __init__(self):
        self._conn = None
        self._cursor = None

    def open(self):
        if self._conn is None:
            self._conn = MySQLdb.connect(host = config.MYSQL_HOST,
                        port = config.MYSQL_PORT,
                        user = config.MYSQL_USER,
                        passwd = config.MYSQL_PASSWORD,
                        db = config.CNBOOKS_DB)

        self._conn.set_character_set('utf8')

        if self._cursor is None:
            self._cursor = self._conn.cursor()
            self._cursor.execute('SET NAMES utf8;')
            self._cursor.execute('SET CHARACTER SET utf8;')
            self._cursor.execute('SET character_set_connection=utf8;')

    def close(self):
        if self._cursor is not None:
            self._cursor.close()

        if self._conn is not None: 
            self._conn.close()

    def execute(self, sql):
        if self._conn is None or self._cursor is None:
            self.open()

        try:
            result = self._cursor.execute(sql)
            self._conn.commit()
            return result
        except Exception, e:
            self._conn.rollback()
            raise e

    def save_or_update(self, sql):
        return self.execute(sql)

    def delete(self, sql):
        return self.execute(sql)

    def select(self, sql):
        if self._conn is None or self._cursor is None:
            self.open()

        result = self._cursor.execute(sql)
        rows = self._cursor.fetchall()
        return rows


